const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs').promises;
const crypto = require('crypto-js');
const { fork } = require('child_process');

let mainWindow;

app.commandLine.appendSwitch('disable-features', 'TextInputClientMac');

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 800,  // 将高度从 600 改为 800
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false
    }
  });

  mainWindow.loadFile('index.html');
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

ipcMain.handle('select-exe', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openFile'],
    filters: [
      { name: 'Executable', extensions: ['exe', 'out', 'app'] }
    ]
  });
  return result.filePaths[0];
});

ipcMain.handle('encrypt-and-package', async (event, filePath, authCode) => {
  try {
    console.log('Starting encryption process');
    const packagerProcess = fork(path.join(__dirname, 'packager.js'));
    packagerProcess.send({ filePath, authCode });

    return new Promise((resolve, reject) => {
      packagerProcess.on('message', (message) => {
        console.log('Received message from packager:', message);
        if (message.type === 'progress') {
          mainWindow.webContents.send('packaging-progress', message.progress);
        } else if (message.type === 'complete') {
          resolve(`加密文件保存在: ${message.outputPath}`);
        } else if (message.type === 'error') {
          reject(new Error(message.error));
        }
      });

      packagerProcess.on('error', (error) => {
        console.error('Packager process error:', error);
        reject(error);
      });

      packagerProcess.on('exit', (code) => {
        console.log('Packager process exited with code:', code);
        if (code !== 0) {
          reject(new Error(`Packager process exited with code ${code}`));
        }
      });
    });
  } catch (error) {
    console.error('加密过程中出错:', error);
    throw error;
  }
});
